package com.study.spark.scala.nginx.util

import java.util.{Date, Locale}

import org.apache.commons.lang3.time.FastDateFormat

/**
  *
  * @author: stephen.shen
  * @create: 2019-03-08 17:05
  */
object DateUtils {
  //输入文件日期格式，FastDateFormat是线程安全的
  val YYYYMMDDHHMM_TIME_FORMAT = FastDateFormat.getInstance("dd/MMM/yyyy:HH:mm:ss Z", Locale.ENGLISH)
  //目标格式
  val TARGET_FORMAT = FastDateFormat.getInstance("yyyy-MM-dd HH:mm:ss")

  val DATE_FORMAT = FastDateFormat.getInstance("yyyy-MM-dd")
  val TIME_FORMAT = FastDateFormat.getInstance("HH:mm:ss")

  def parse(time: String) = {
    TARGET_FORMAT.format(new Date(getTimestamp(time)))
  }

  def getTimestamp(time: String) = {
    try {
      YYYYMMDDHHMM_TIME_FORMAT.parse(time.substring(time.indexOf("[") + 1,
        time.lastIndexOf("]"))).getTime
    } catch {
      case e: Exception => {
        0l
      }
    }
  }

  def getDate(datetime: String): String = {
    DATE_FORMAT.format(TARGET_FORMAT.parse(datetime))
  }

  def getTime(datetime: String): String = {
    TIME_FORMAT.format(TARGET_FORMAT.parse(datetime))
  }

  def main(args: Array[String]): Unit = {

    println(parse("[03/Aug/2017:18:14:11 +0800]"))
    println(getDate(parse("[03/Aug/2017:18:14:11 +0800]")))
    println(getTime(parse("[03/Aug/2017:18:14:11 +0800]")))
  }

}
